import React, { Component } from 'react'
import './App.css'
class App extends Component {
  constructor () {
    super()
    this.state = {
      todos: [
        { isComplete: false, id: 1, content: 'JAVA'},
        { isComplete: true, id: 2, content: 'javascript'},
        { isComplete: false, id: 3, content: 'C++'}
      ],
      newContent: '',
      editId: -1,
      leftCount: 0,
      isToggleAll: false,
      showClear: false,
      filterValue: ''
    }
  }
  // 1、渲染列表页面
  renderList () {
    let { todos, editId, filterValue } = this.state
    return todos.map(todo => {
      if (filterValue === '#/active' && todo.isComplete) return null
      if (filterValue === '#/completed' && !todo.isComplete) return null
      return (
        <li key={todo.id} className={todo.isComplete? 'completed ' : ' ' + editId === todo.id ? 'editing': ''}>
          <div className="view">
              <input className="toggle" type="checkbox" checked={todo.isComplete} onChange={e => this.checkedHandler(e, todo)}/>
              <label onDoubleClick={e => this.beginEdit(e, todo)}>{todo.content}</label>
              <button className="destroy" onClick={e => this.deleteTodo(e, todo)}></button>
          </div>
          <form onSubmit={e => this.editOver(e)}>
            <input className="edit" ref={'todo_'+ todo.id} value={todo.content}
              onChange={e => this.saveEdit(e, todo)} onBlur={e => this.editOver(e)} />
          </form>
        </li>
      )
    })
  }
  componentDidMount () {
    this.computedLeftCount()
    this.renderByHash()
  }
  // 2、新增数据
  addTodo (e) {
    this.setState({newContent: e.target.value})
  }
  addBlurHandler (e) {
    // 阻止默认事件
    e.preventDefault()
    let { newContent, todos } = this.state
    if (!newContent.trim()) return
    let max = -1
    todos.forEach(todo  => {
      if ( todo.id > max) max = todo.id
    })
    max++
    todos.push({id:max, content: newContent, isComplete: false})
    this.setState({newContent: '', todos})
    this.computedLeftCount()
  }
  // 3、点击复选框
  checkedHandler (e, todo) {
    let {checked} = e.target
    todo.isComplete = checked
    this.computedLeftCount()
    // this.setState({})
  }
  // 4、双击内容用来编辑
  beginEdit (e, todo) {
    this.setState({ editId: todo.id }, () => {
      // 获取焦点
      this.refs['todo_' + todo.id].focus()
    })
  }
  saveEdit (e, todo) {
    todo.content = e.target.value
    this.setState({})
  }
  // 5、结束编辑
  editOver (e) {
    e.preventDefault()
    this.setState({editId: -1})
  }
  // 6、删除数据
  deleteTodo (e, todo) {
    let {todos} = this.state
    let index = todos.findIndex(el => el.id === todo.id)
    todos.splice(index, 1)
    // this.setState({todos}, ()=> {
    //   console.log(this.state.todos)
    // })
    // this.setState({})
    this.computedLeftCount()
  }
  // 计算左侧的数据
  computedLeftCount () {
    let { todos, showClear, isToggleAll } = this.state
    let leftCount = 0
    showClear = false
    isToggleAll = true
    todos.forEach(todo => {
      // 没有完成的数据
      if (!todo.isComplete) {
        leftCount++
        // 当找到一个falsetoggleAll就是false了
        isToggleAll = false
      } else {
        showClear = true
      }
    })
    this.setState({leftCount, showClear, isToggleAll})
  }
  toggleAllNode (e) {
    let { todos, leftCount } = this.state
    let { checked } = e.target
    todos.forEach(todo => {
      todo.isComplete = checked
    })
    leftCount = checked ? todos.length : 0
    this.setState({ todos, isToggleAll: checked, leftCount })
  }
  // 清除所有的完成
  clearAllCompleted (e) {
    let { todos } = this.state
    for (let index = todos.length - 1; index >= 0; index--) {
      if (todos[index].isComplete) todos.splice(index, 1) 
    }
    this.setState({todos})
    this.computedLeftCount()
  }
  // 过滤元素
  filterElement (e) {
    this.setState({filterValue: e.target.hash})
  }
  // 根据hash来过滤
  renderByHash () {
    let {filterValue} = this.state
    filterValue = window.location.hash
    window.addEventListener('hashchange', () => {
      filterValue = window.location.hash
      this.setState({filterValue})
    })
  }
  render () { 
    let { isToggleAll, newContent, leftCount, showClear, filterValue } = this.state
    return (
      <div>
        <section className="todoapp">
          <header className="header">
            <h1>todos</h1>
            <form onSubmit={e => this.addBlurHandler(e)}>
              <input className="new-todo" placeholder="What needs to be done?" autoFocus
                onChange={e => this.addTodo(e)} value={newContent} onBlur={e => this.addBlurHandler(e)}/>
            </form>
          </header>
          {/* This section should be hidden by default and shown when there are todos */}
          <section className="main">
            <input id="toggle-all" className="toggle-all" type="checkbox"
              checked={ isToggleAll } onChange={e => this.toggleAllNode(e)} />
            <label htmlFor="toggle-all">Mark all as complete</label>
            <ul className="todo-list">
              {/* These are here just to show the structure of the list items */}
              {/* List items should get the className `editing` when editing and `completed` when marked as completed */}
              {this.renderList()}
            </ul>
          </section>
          {/* This footer should hidden by default and shown when there are todos */}
          <footer className="footer">
            {/* This should be `0 items left` by default */}
            <span className="todo-count">
              <strong>{leftCount}</strong> item left
            </span>
            {/* Remove this if you don't implement routing */}
            <ul className="filters">
              <li>
                <a className={filterValue !== '#/active' && filterValue !== '#/completed' ? 'selected' : ''}
                  href="#/" onClick={e => this.filterElement(e)}>All</a>
              </li>
              <li>
                <a className={filterValue === '#/active' ? 'selected' : ''} href="#/active" onClick={e => this.filterElement(e)} >Active</a>
              </li>
              <li>
                <a className={filterValue === '#/completed' ? 'selected' : ''} href="#/completed" onClick={e => this.filterElement(e)} >Completed</a>
              </li>
            </ul>
            {/*Hidden if no completed items are left ↓ */}
            {showClear && <button className="clear-completed" onClick={e => this.clearAllCompleted(e)}>Clear completed</button>}
          </footer>
        </section>
        <footer className="info">
          <p>Double-click to edit a todo</p>
          {/* Remove the below line ↓ */}
          <p>Template by <a href="http://sindresorhus.com">Sindre Sorhus</a></p>
          {/* Change this out with your name and url ↓ */}
          <p>Created by <a href="http://todomvc.com">you</a></p>
          <p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
        </footer>
      </div>
    )
  }
}
export default App
